import os, cgi
import pymysql as db
import cgitb; cgitb.enable()

conn = db.connect (host = "localhost",
            user = "student",
            passwd = "anything",
            db = "emanuelacademy")
cursor = conn.cursor()

env = os.environ.get
formData = cgi.FieldStorage()

user = env('AUTH_USER').strip()
try:
    alias = formData['userAlias'].value
except:
    alias = ''

fullName = user.split('.')
if len(fullName) == 1:
    firstName = 'The'
    lastName = fullName[0][1:].title()
else:
    firstName = fullName[1]
    lastName = fullName[0]

defaultAlias = firstName + ' ' + lastName

cursor.execute("SELECT * FROM users WHERE username = '%s'" %user) 
row = cursor.fetchone()

def getData():
    cursor.execute("SELECT * FROM users WHERE username = '%s'" %user)
    row = cursor.fetchone()
    if row == None:
        cursor.execute('''INSERT INTO users (userID, username, alias, totalPoints)
                       VALUES (NULL, '%s', '%s', 0)
                       ''' %(user, defaultAlias.title()))
    conn.commit()
    cursor.execute("SELECT * FROM users WHERE username = '%s'" %user)
    row = cursor.fetchone()
    userID, username, userAlias, totalPoints, position, streak, correct, attempted = row
    return userID, username, userAlias, totalPoints, position, streak, correct, attempted

def getUserAlias():
    return getData()[2]

def getTotalPoints():
    return getData()[3]

def getUserPosition():
    return getData()[4]

def getCurrentStreak():
    return getData()[5]

def getCorrect():
    return getData()[6]

def getAttempted():
    return getData()[7]
